package com.zyh.alpacaSse.service;


import com.zyh.alpacaSse.pojo.JournalEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

/**
 * @Classname EventProcessor
 * @Description TODO()
 * @Date 2025-09-03 22:53
 * @Created by 86177
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class EventProcessor {

    private final AlpacaSseService sseService;

    @EventListener(ContextRefreshedEvent.class)
    public void startProcessing() {
        sseService.streamEvents()
                .subscribe(
                        // 正常处理
                        this::handleEvent,
                        // 错误处理
                        this::handleError,
                        // 完成处理
                        this::handleComplete
                );
    }

    private void handleEvent(JournalEvent event) {
        log.info("Processing event: {}", event.getId());

        // 根据状态进行业务处理
        switch (event.getData().getStatus()) {
            case "processed":
                processCompletedJournal(event);
                break;
            case "rejected":
                processRejectedJournal(event);
                break;
            case "pending":
                log.debug("Journal pending: {}", event.getData().getJournal_id());
                break;
            default:
                log.warn("Unknown journal status: {}", event.getData().getStatus());
        }
    }

    private void processCompletedJournal(JournalEvent event) {
        log.info("Journal processed: {}", event.getData().getJournal_id());
        // 业务逻辑: 更新数据库、触发通知等
    }

    private void processRejectedJournal(JournalEvent event) {
        log.warn("Journal rejected: {}", event.getData().getJournal_id());
        // 获取拒绝原因
        String reason = (String) event.getData().getDetails().getOrDefault("reason", "Unknown");
        log.error("Rejection reason: {}", reason);

        // 业务逻辑: 发送告警、重试等
    }

    private void handleError(Throwable error) {
        log.error("Event processing error", error);
        // 业务逻辑: 告警通知、错误恢复等
    }

    private void handleComplete() {
        log.warn("Event stream completed unexpectedly");
        // 业务逻辑: 重启监听等
    }
}
